<template>
  <div class="notebookClass">
    <el-card class="box-card">
       
      <div slot="header" class="clearfix">
        <span style="font-weight:bold;">我的便签</span>
          <i
          v-show="!isPanelSetIcon"
          class="el-icon-close"
          style="float: right; padding: 3px 0"
          @click="deletePanelItem"
        ></i>
        <el-button v-show="isPanelSetIcon"  style="float: right; padding: 3px 0" type="text" icon="el-icon-plus" @click="addNoteBook"></el-button>
      </div>
          <avue-crud :option="option"
                :table-loading="loading"
                :data="data"
                ref="noteCrud"
                v-model="form"
                :defaults.sync="showColumn"
                :permission="permissionList"
                :page.sync="page"
                :before-open="beforeOpen"
                @sortable-change="sortableChange"
                @row-del="rowDel"
                @row-update="rowUpdate"
                @row-save="rowSave"
                @refresh-change="refreshChange"
                @search-change="searchChange"
                @search-reset="searchReset"
                @selection-change="selectionChange"
                @current-change="currentChange"
                @size-change="sizeChange"
                @filter="filterChange"
                @sort-change="sortChange"
                @cell-mouse-enter="cellMouseEnter"
                @cell-mouse-leave="cellMouseLeave"
                @row-dblclick="handleRowDBLClick"               
                @on-load="onLoad">
            <template slot="title" slot-scope="scope" >
              <span :style="'color:'+scope.row.titleColor">{{scope.row.title}}</span>
            </template>
            <template slot-scope="scope" slot="menu">
              <el-button v-if="scope.row.show" type="text"
                        size="small"
                        icon="el-icon-delete"
                        @click.stop="rowDel(scope.row)">
              </el-button>
              <div v-if="!scope.row.show" style="font-size:8px;">
                {{scope.row.createDatetime.substring(5,10).replace('-','/')}}
              </div>
            </template>
        </avue-crud>
    </el-card>
  </div>
</template>

<script>
import {exportGeneralNoteBookExcel,saveOrUpdateGeneralNoteBook,saveOrUpdateGeneralNoteBookList,saveGeneralNoteBook,saveGeneralNoteBookList,deleteGeneralNoteBook,queryGeneralNoteBook,queryGeneralNoteBookListPage,updateGeneralNoteBook,deleteGeneralNoteBookList} from '@/api/general/note/generalNoteBookApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat} from '@/util/util';
import updateHistory from '@/views/components/history/update-history.vue'
export default {
  components: {
    updateHistory
  },
  props: ['id', 'panelSetIcon'],
  data () {
    return {
      panelId: this.id,
      isPanelSetIcon: this.panelSetIcon,
      
      //修改记录对话框
      historyDialog: false,
      //如果做流程表单 请将次开关设置为true，否则设置为false
      isFlowFrom: true,
      
      importDataArea: '',
      batchAddDialog: false,
      form: {},
      selectionList: [],
      loading: true, 
      showColumn: [],
      option: {
        index: false,
        columnBtn: false,
        addBtn: false,
        delBtn: false,
        editBtn:false,
        viewBtn: false,
        refreshBtn: false,
        stripe:true,
        menu: true,
        editTitle: '我的纸条',
        menuWidth: 60,
        dialogMenuPosition: 'center',
        emptyText: '暂无待处理的任务',
        column: [
          {
            label: '标题',
            prop: 'title', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 24,
            hide: false,
            maxlength: 200,
            overHidden: true,
            slot:true,
            rules: [{
              required:  true,
              trigger: 'blur',
              message: '请输入标题',
            },
            {
              max: 200,
              message: '内容长度不能超过200字符',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '分类',
            prop: 'category', 
            type: 'select', 
            span: 6,
            hide: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            },
            {
              max: 30,
              message: '内容长度不能超过30字符',
              trigger: 'blur'
            }],
            value: '日常记录',
            dicData:[
              {
                label: '日常记录',
                value: '日常记录'
              },
              {
                label: '项目记录',
                value: '项目记录'
              },
              {
                label: '其他记录',
                value: '其他记录'
              }
            ]
          },
          {
            label: '状态',
            prop: 'status', 
            type: 'radio', 
            span: 10,
            hide: true,
            maxlength: 30,
            value: '0',
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            },
            {
              max: 30,
              message: '内容长度不能超过30字符',
              trigger: 'blur'
            }],
            dicData:[
              {
                label: '未开始',
                value: '0'
              },
              {
                label: '进行中',
                value: '1'
              },
              {
                label: '已完成',
                value: '2'
              }
            ]
          },
          
          {
            label: '标记色',
            prop: 'titleColor',
            type: 'color',
            hide: true,
            span: 8,
          },
          {
            type: 'ueditor',
            component: 'avue-ueditor',
            label: '内容',
            size: 'small',
            prop: 'content',
            span: 24,
            display: true,
            disabled: false,
            hide: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            options: {
              action: '/file/upload',
              props: {
                res: '',
                url: 'filePath'
              },
            }
          },
          {
            label: '创建日期',
            prop: 'createDatetime', 
            type: 'input',  
            span: 12,
            hide: true,
            addDisplay: false,
            disabled: true
          },
          {
            label: '修改日期',
            prop: 'updateDatetime', 
            type: 'input',  
            span: 12,
            hide: true,
            addDisplay: false,
            disabled: true
          },
        ]
      },
      data: [],
      // 请求参数区
      page: {
        pageSize: 5,
        currentPage: 1,
        total: 0,
        layout: 'total,pager,prev, next',
        background:false,
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  computed: {
    ...mapGetters(['website','orgTree','userInfo','permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.general_note_book_add, false),
        viewBtn: this.vaildData(this.permission.general_note_book_view, false),
        delBtn: this.vaildData(this.permission.general_note_book_delete, false),
        editBtn: this.vaildData(this.permission.general_note_book_edit, false),
        printBtn: this.vaildData(this.permission.general_note_book_print, false),
        searchBtn:this.vaildData(this.permission.general_note_book_search, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: {
    /**
     * 进入单元格
     */
    cellMouseEnter(row, column, cell, event){
      row.show = true;
      row.title=row.title+' ';
    },
    /**
     * 离开单元格
     */
    cellMouseLeave(row, column, cell, event){
      row.show = false;
      row.title=row.title.trim();
    },
    /**
     * 打开修改历史对话框
     */
    openHistoryDialog(){
      //this.$console.log('修改历史....');
      this.historyDialog = true;
    },
    /**
     * 调用子组件方法查询历史
     */
    getHistoryRecord () {
      setTimeout(() => {
        this.$refs.historyRecord.getUpdateHistoryRecord(this.form.id);
      })
    },
    /**
     * 加载列表数据
     */
    onLoad(page) {
      this.loading = true;
      this.orderRules = {
        order: 'descending',
        prop: 'create_datetime'
      }
      this.reqParams =  {
        singleBody: {
          userId:  this.userInfo.userId
        },
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: page.currentPage, 
        pageSize: page.pageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      queryGeneralNoteBookListPage(this.commonData).then(res => {
        const data = res.data.body;
        this.page.total = data.total;
        this.data = data.listBody;
        this.data.forEach(element => {
          element.show=false;
        });
        this.loading = false;
      }, error => {
        this.loading = false; 
      });
    },
    /**
     * 添加一条记录
     */
    addNoteBook(){
      this.$refs.noteCrud.rowAdd();
    },
    /**
     * 新增一条记录
     */
    rowSave(row, done, loading) {
      this.reqParams.singleBody = row;
      this.reqParams.singleBody.userId = this.userInfo.userId;
      this.commonData = reqCommonMsg(this.reqParams)
      saveGeneralNoteBook(this.commonData).then(() => {
        done();
        this.singleBody={};
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        done();
      });         
      //this.$console.log("row = ",row ,loading)
    },
    /**
     * 双击修改记录
     */
    handleRowDBLClick(row){
      this.$refs.noteCrud.rowEdit(row,row.$index);
    },
    /**
     * 修改一条记录
     */
    rowUpdate(row, index, done, loading) {
      this.reqParams.singleBody = row;
      this.commonData = reqCommonMsg(this.reqParams)
      updateGeneralNoteBook(this.commonData).then(() => {
        done();
        this.singleBody={}
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        done();
      });
    },
    /**
     * 删除一条记录
     */
    rowDel(row) {
      //this.$console.log('row==',row)
      this.$confirm('确定删除纸条?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.singleBody = row;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteGeneralNoteBook(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
        }).catch(() => {});
    },
    
    /**
     * 批量新增记录
     */
    openBatchAddDialog(){
      this.batchAddDialog = true;
    },
    /**
     * 批量导入
     */
    handleImport() {
      const loading = this.$loading({
        lock: true,
        text: '处理中...',
        spinner: 'el-icon-loading',
      });
      var dataList = new Array();
      if(this.importDataArea){
        var lineList = this.importDataArea.split('\n')
        lineList.forEach((element,index) => {
          if(element.trim() != ''){
            var field = element.split('\t')
            var fieldList = {
              category:field[0].trim(),
              title:field[1].trim(),
              content:field[2].trim(),
              status:field[3].trim(),
            }
            dataList[index] = fieldList
            //this.$console.log('fieldList = ',fieldList)
          }
        });
        //批量写入记录
        this.reqParams.listBody = dataList;
        this.commonData = reqCommonMsg(this.reqParams)
        saveGeneralNoteBookList(this.commonData).then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          loading.close();
        }, error => {
          //this.$console.log(error);
          loading.close();
        });      
      }
      else{
        this.loading=false;
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '数据格式不正确!'
        });
      }
    },
    /**
     * 搜索重置
     */
    searchReset() {
      this.conditions =[];
      this.singleBody = {};
      this.onLoad(this.page);
    },
    /**
     * 搜索
     */
    searchChange(params, done) {
      this.singleBody = params
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    refreshChange(){
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.noteCrud.toggleSelection();
    },
    /**
     * 处理批量删除
     */
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.listBody = this.ids;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteGeneralNoteBookList(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.noteCrud.toggleSelection();
        }).catch(() => {});
    },
    /**
     * 拷贝记录
     */
    handleCopy(row){
      this.$confirm('确定复制数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading=true;
        let copyValue=row;
        copyValue.id='0';
        copyValue.dataSign='0'
        copyValue.tableName='拷贝 '+ copyValue.tableName; 
        this.reqParams.singleBody = copyValue;
        this.commonData = reqCommonMsg(this.reqParams)
        saveSysToolTables(this.commonData).then(() => {
          this.singleBody={};
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.loading=false;
        }, error => {
          //this.$console.log(error);
          this.loading=false;
        });
      }).catch(() => {});       
    },
    /**
     * 打开编辑、查询弹窗前查询记录
     */  
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        this.reqParams =  {
          singleBody: {
            id:this.form.id
          }
        }
        let commonData = reqCommonMsg(this.reqParams)
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading'
        });
        queryGeneralNoteBook(commonData).then(res => {
          this.form = res.data.body.singleBody;
          loading.close();
          done();
        }, error => {
          //this.$console.log(error);
          loading.close();
          done();
        });
      }
      if (['add'].includes(type)) {
     	done();
      }
    },
    /**
     * 翻页查询
     */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /**
     * 更改每页条数
     */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /**
     * 自定义查询条件
     */
    filterChange(result) {
      this.page.currentPage = 1;
      this.conditions = filterFormat(result)
      this.onLoad(this.page);
    },
    /**
     * 列表排序
     */
    sortChange(val){
      this.orderRules=val
      this.onLoad(this.page);
    },
  
    /**
     * 导出Excel
     */
    exportExcel() {
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage:1, 
        pageSize: 100
      }
      //this.$console.log('reqParams = ',this.reqParams)
      this.commonData = reqCommonMsg(this.reqParams)
      exportGeneralNoteBookExcel(this.commonData);
    },
    /**
     * 获取业务字典参数
     */
    async getBizDict() {
      let dicData = await this.$params.getBizDict('["bizType"]');
      this.findObject(this.option.column, 'bizType').dicData = dicData.bizType;
    },
    // 删除面板项发送事件
    deletePanelItem () {
      this.$emit('deletePanelItemEvent', this.panelId)
    }
  },
  created() {
       
  },
  mounted() {
    
  }
};
</script>
<style>
 .notebookClass .el-table__header{
   display: none !important;
 }
 .notebookClass .avue-crud__menu{
   display: none !important;
 }
 .notebookClass .avue-crud__pagination{
   padding:5px !important;
   margin: 0px !important;
 }
 .notebookClass .el-card__body{
   padding:0px!important;
 }
</style>
